<template>
	<view class="container">
		<!-- 自定义导航栏 -->
		<u-navbar
			:is-back="true"
			:title="singer.name || '歌手详情'"
			:border-bottom="false"
			:custom-back="true"
			@back="goBack"
			:background="{ background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' }"
			title-color="#ffffff"
		/>

		<!-- 歌手信息卡片 -->
		<view class="singer-card">
			<view class="singer-bg"></view>
			<view class="singer-content">
				<image :src="singer.avatar || singer.singer_avatar || '/static/singer/default.jpg'" class="singer-avatar" mode="aspectFill" @error="onAvatarError" />
				<view class="singer-details">
					<view class="singer-name">{{ singer.name || singer.singer_name || '未知歌手' }}</view>
					<view class="singer-desc">{{ singer.description || '华语流行音乐歌手' }}</view>
					<view class="singer-stats">
						<view class="stat-item">
							<text class="stat-number">{{ totalSongs }}</text>
							<text class="stat-label">首歌曲</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 歌曲列表标题 -->
		<view class="section-header">
			<view class="section-title">
				<u-icon name="music-note" size="24" color="#667eea"></u-icon>
				<text class="title-text">热门歌曲</text>
			</view>
			<view class="section-count">共{{ totalSongs }}首</view>
		</view>

		<!-- 歌曲列表 -->
		<scroll-view
			scroll-y
			class="songs-scroll"
			@scrolltolower="loadMoreSongs"
			:refresher-enabled="true"
			:refresher-triggered="isRefreshing"
			@refresherrefresh="onRefresh"
			:lower-threshold="100"
		>
			<!-- 加载状态 -->
			<view v-if="isLoading && singerSongs.length === 0" class="loading-container">
				<view class="loading-spinner"></view>
				<text class="loading-text">正在加载歌曲...</text>
			</view>

			<!-- 歌曲列表 -->
			<view v-else-if="singerSongs.length > 0" class="songs-list">
				<view v-for="(song, idx) in singerSongs" :key="idx" class="song-item">
					<view class="song-index">
						<text class="index-number">{{ idx + 1 }}</text>
					</view>
					<view class="song-info" @click="playSong(song)">
						<view class="song-title">{{ song.song_name }}</view>
						<view class="song-meta">
							<text class="song-artist">{{ song.singer_name }}</text>
							<view class="song-type" v-if="song.type">
								<text class="type-tag">{{ getTypeText(song.type) }}</text>
							</view>
						</view>
					</view>
					<view class="song-actions">
						<view class="action-btn" @click="handleOrderSong(song, idx)">
							<u-icon name="plus-circle" size="40" :color="orderId ? '#667eea' : '#999999'"></u-icon>
						</view>
						<!-- <view class="action-btn" @click="handleShowSongMenu(song, idx)">
							<u-icon name="more-dot-fill" size="40" color="#999999"></u-icon>
						</view> -->
					</view>
				</view>
			</view>

			<!-- 空状态 -->
			<view v-else-if="!isLoading" class="empty-state">
				<view class="empty-icon">🎵</view>
				<view class="empty-title">暂无歌曲</view>
				<view class="empty-desc">该歌手暂时没有歌曲</view>
			</view>

			<!-- 加载更多 -->
			<view v-if="isLoadingMore" class="loading-more">
				<view class="loading-spinner-small"></view>
				<text class="loading-more-text">加载更多...</text>
			</view>

			<!-- 没有更多 -->
			<view v-if="!hasMore && singerSongs.length > 0" class="no-more">
				<text class="no-more-text">没有更多歌曲了</text>
			</view>
		</scroll-view>

		<!-- 歌曲操作菜单 -->
		<u-popup v-model="showSongActionPopup" mode="bottom" border-radius="20" :mask-close-able="true">
			<view class="song-action-popup">
				<view class="popup-header">
					<view class="popup-song-info">
						<view class="popup-song-details">
							<view class="popup-song-title">{{ currentSong.song_name }}</view>
							<view class="popup-song-artist">{{ currentSong.singer_name }}</view>
						</view>
					</view>
				</view>
				<view class="action-list">
					<view class="action-item-popup" @click="orderSongFromPopup">
						<u-icon name="plus-circle" size="32" color="#667eea" />
						<text class="action-text-popup">点歌</text>
					</view>
					<view class="action-item-popup" @click="grabSongFromPopup">
						<u-icon name="play-circle" size="32" color="#4ecdc4" />
						<text class="action-text-popup">抢歌</text>
					</view>
					<view class="action-item-popup" @click="pinSongFromPopup">
						<u-icon name="pushpin" size="32" color="#45b7d1" />
						<text class="action-text-popup">置顶</text>
					</view>
				</view>
				<u-button type="default" class="cancel-btn" @click="showSongActionPopup = false">取消</u-button>
			</view>
		</u-popup>

		<!-- 播放预览弹窗 -->
		<u-popup v-model="showPlayPopup" mode="center" border-radius="20" width="600rpx">
			<view class="play-popup">
				<view class="play-header">
					<text class="play-title">歌曲预览</text>
					<u-icon name="close" size="24" color="#999" @click="showPlayPopup = false" />
				</view>
				<view class="play-content">
					<view class="play-info">
						<view class="play-song-title">{{ currentSong.song_name }}</view>
						<view class="play-song-artist">{{ currentSong.singer_name }}</view>
					</view>
					<view class="play-controls">
						<u-icon name="play-circle" size="60" color="#667eea" @click="togglePlay" />
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
import request from '@/common/request.js';
import ktvCommand from '@/common/ktv-command-utils.js';

export default {
	data() {
		return {
			orderId: '',
			singerId: '',
			singerName: '',
			singer: {
				name: '',
				singer_name: '',
				avatar: '',
				singer_avatar: '',
				description: ''
			},
			singerSongs: [],
			totalSongs: 0,
			currentSong: {},
			currentSongIndex: -1,
			showSongActionPopup: false,
			showPlayPopup: false,
			isLoading: false,
			isLoadingMore: false,
			isRefreshing: false,
			hasMore: true,
			currentPage: 1,
			// 防抖控制
			lastCommandTime: 0,
			commandCooldown: 1000
		};
	},
	onLoad(options) {
		console.log('歌手详情页面参数:', options);
		this.orderId = options.order_id || '';
		this.singerId = options.singer_id || '';
		this.singerName = decodeURIComponent(options.singer_name || options.name || '');
		this.singer.avatar = options.avatar || options.singer_avatar || '';

		if (!this.orderId) {
			uni.showModal({
				title: '提示',
				content: '缺少订单信息',
				showCancel: false,
				success: () => {
					uni.navigateBack();
				}
			});
			return;
		}

		// 设置歌手基本信息
		this.singer.name = this.singerName;
		this.singer.singer_name = this.singerName;

		this.loadSingerSongs();
	},
	methods: {
		goBack() {
			uni.navigateBack();
		},

		// 检查是否可以执行命令
		canExecuteCommand() {
			const now = Date.now();
			const timeSinceLastCommand = now - this.lastCommandTime;

			if (timeSinceLastCommand < this.commandCooldown) {
				const remainingTime = Math.ceil((this.commandCooldown - timeSinceLastCommand) / 1000);
				uni.showToast({
					title: `请等待${remainingTime}秒后再操作`,
					icon: 'none',
					duration: 1000
				});
				return false;
			}

			return true;
		},

		// 更新最后命令时间
		updateLastCommandTime() {
			this.lastCommandTime = Date.now();
		},

		// 头像加载错误处理
		onAvatarError() {
			this.singer.avatar = '/static/singer/default.jpg';
		},

		// 获取歌曲类型文本
		getTypeText(type) {
			const typeMap = {
				1: 'MTV',
				2: '伴奏',
				3: '原唱'
			};
			return typeMap[type] || 'MTV';
		},

		// 加载歌手歌曲
		async loadSingerSongs(isRefresh = false) {
			if (isRefresh) {
				this.currentPage = 1;
				this.hasMore = true;
				this.isRefreshing = true;
			} else if (this.currentPage === 1) {
				this.isLoading = true;
			} else {
				this.isLoadingMore = true;
			}

			try {
				const res = await request.httpTokenRequest({
					url: `/api/ktv/getSongListBySinger?order_id=${this.orderId}&page=${this.currentPage}&singer_name=${encodeURIComponent(this.singerName)}`,
					method: 'get'
				});

				console.log('歌手歌曲接口返回:', res.data);

				if (res.data.code === 1) {
					const responseData = res.data.data;
					const songs = responseData.data || [];

					// 过滤无效歌曲数据
					const validSongs = songs.filter((song) => {
						return song && song.song_id && song.song_name;
					});

					if (isRefresh || this.currentPage === 1) {
						this.singerSongs = validSongs;
					} else {
						this.singerSongs = [...this.singerSongs, ...validSongs];
					}

					// 更新总数和分页信息
					this.totalSongs = responseData.total || 0;
					this.hasMore = responseData.has_more_page || false;

					console.log('获取歌手歌曲成功，当前页:', this.currentPage, '歌曲数量:', validSongs.length, '总数:', this.totalSongs);
				} else {
					throw new Error(res.data.msg || '获取歌曲列表失败');
				}
			} catch (error) {
				console.error('获取歌手歌曲失败:', error);
				uni.showToast({
					title: error.message || '获取歌曲失败',
					icon: 'none'
				});
			} finally {
				this.isLoading = false;
				this.isLoadingMore = false;
				setTimeout(() => {
					this.isRefreshing = false;
				}, 500);
			}
		},

		// 下拉刷新
		onRefresh() {
			this.loadSingerSongs(true);
		},

		// 上拉加载更多
		loadMoreSongs() {
			if (this.isLoadingMore || !this.hasMore) return;
			this.currentPage++;
			this.loadSingerSongs();
		},

		// 播放歌曲
		playSong(song) {
			console.log('播放歌曲:', song);
			this.currentSong = song;
			this.showPlayPopup = true;
		},

		// 切换播放状态
		togglePlay() {
			uni.showToast({
				title: '播放功能开发中',
				icon: 'none'
			});
		},

		// 处理点歌按钮点击
		handleOrderSong(song, index) {
			console.log('handleOrderSong 被调用');
			console.log('song:', song);
			console.log('index:', index);

			if (!song || !song.song_id) {
				console.error('歌曲数据异常:', song);
				uni.showToast({
					title: '歌曲数据异常',
					icon: 'none'
				});
				return;
			}

			this.orderSong(song);
		},

		// 处理显示歌曲菜单
		handleShowSongMenu(song, index) {
			console.log('handleShowSongMenu 被调用');
			console.log('song:', song);
			console.log('index:', index);

			this.currentSong = song;
			this.currentSongIndex = index;
			this.showSongActionPopup = true;
		},

		// 点歌功能
		async orderSong(song) {
			console.log('orderSong 被调用');
			console.log('传入的 song 参数:', song);

			if (!song || !song.song_id) {
				console.error('歌曲数据异常:', song);
				uni.showToast({
					title: '歌曲数据异常',
					icon: 'none'
				});
				return;
			}

			if (!this.canExecuteCommand()) return;
			this.updateLastCommandTime();

			const success = await ktvCommand.addSong(this.orderId, song.song_id);

			if (success) {
				uni.showToast({
					title: `已点：${song.song_name}`,
					icon: 'success'
				});
			}
		},

		// 从弹窗点歌
		orderSongFromPopup() {
			console.log('从弹窗点歌:', this.currentSong);
			this.orderSong(this.currentSong);
			this.showSongActionPopup = false;
		},

		// 从弹窗抢歌
		async grabSongFromPopup() {
			console.log('从弹窗抢歌:', this.currentSong);

			if (!this.currentSong || !this.currentSong.song_id) {
				uni.showToast({
					title: '歌曲数据异常',
					icon: 'none'
				});
				return;
			}

			if (!this.canExecuteCommand()) return;
			this.updateLastCommandTime();

			const success = await ktvCommand.insertSong(this.orderId, this.currentSong.song_id);

			if (success) {
				uni.showToast({
					title: `已抢歌：${this.currentSong.song_name}`,
					icon: 'success'
				});
			}
			this.showSongActionPopup = false;
		},

		// 从弹窗置顶
		async pinSongFromPopup() {
			console.log('从弹窗置顶:', this.currentSong);

			if (!this.currentSong || !this.currentSong.song_id) {
				uni.showToast({
					title: '歌曲数据异常',
					icon: 'none'
				});
				return;
			}

			if (!this.canExecuteCommand()) return;
			this.updateLastCommandTime();

			const success = await ktvCommand.insertSong(this.orderId, this.currentSong.song_id);

			if (success) {
				uni.showToast({
					title: `已置顶：${this.currentSong.song_name}`,
					icon: 'success'
				});
			}
			this.showSongActionPopup = false;
		}
	}
};
</script>

<style lang="scss" scoped>
.container {
	background: linear-gradient(180deg, #0d0d11 0%, #1a1a1f 100%);
	color: #ffffff;
	min-height: 100vh;
}

// 歌手信息卡片
.singer-card {
	position: relative;
	margin: 20rpx;
	border-radius: 20rpx;
	overflow: hidden;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	box-shadow: 0 8rpx 32rpx rgba(102, 126, 234, 0.3);
}

.singer-bg {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.2);
	backdrop-filter: blur(10rpx);
}

.singer-content {
	position: relative;
	padding: 40rpx 30rpx;
	display: flex;
	align-items: center;
}

.singer-avatar {
	width: 140rpx;
	height: 140rpx;
	border-radius: 50%;
	border: 4rpx solid rgba(255, 255, 255, 0.3);
	box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.3);
}

.singer-details {
	flex: 1;
	margin-left: 30rpx;
}

.singer-name {
	font-size: 40rpx;
	font-weight: bold;
	color: #ffffff;
	margin-bottom: 12rpx;
	text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.3);
}

.singer-desc {
	font-size: 28rpx;
	color: rgba(255, 255, 255, 0.9);
	margin-bottom: 25rpx;
	line-height: 1.4;
}

.singer-stats {
	display: flex;
	justify-content: flex-start;
}

.stat-item {
	display: flex;
	flex-direction: column;
	align-items: center;
}

.stat-number {
	font-size: 32rpx;
	font-weight: bold;
	color: #ffffff;
	text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.3);
}

.stat-label {
	font-size: 24rpx;
	color: rgba(255, 255, 255, 0.8);
	margin-top: 8rpx;
}

// 歌曲列表标题
.section-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx 20rpx 20rpx 20rpx;
}

.section-title {
	display: flex;
	align-items: center;
	gap: 12rpx;
}

.title-text {
	font-size: 32rpx;
	font-weight: bold;
	color: #ffffff;
}

.section-count {
	font-size: 26rpx;
	color: #888888;
	background: rgba(255, 255, 255, 0.05);
	padding: 8rpx 16rpx;
	border-radius: 20rpx;
}

// 歌曲列表
.songs-scroll {
	flex: 1;
	padding: 0 20rpx;
	height: calc(100vh - 350rpx);
}

.songs-list {
	padding-bottom: 40rpx;
}

.song-item {
	display: flex;
	align-items: center;
	background: rgba(255, 255, 255, 0.05);
	border-radius: 16rpx;
	padding: 24rpx;
	margin-bottom: 16rpx;
	backdrop-filter: blur(10rpx);
	border: 1rpx solid rgba(255, 255, 255, 0.1);
	transition: all 0.3s;

	&:active {
		transform: scale(0.98);
		background: rgba(255, 255, 255, 0.1);
	}
}

.song-index {
	width: 50rpx;
	height: 50rpx;
	border-radius: 50%;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 24rpx;
	flex-shrink: 0;
}

.index-number {
	font-size: 24rpx;
	font-weight: bold;
	color: #ffffff;
}

.song-info {
	flex: 1;
	min-width: 0;
	cursor: pointer;
}

.song-title {
	font-size: 32rpx;
	font-weight: 500;
	color: #ffffff;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
	margin-bottom: 12rpx;
	line-height: 1.3;
}

.song-meta {
	display: flex;
	align-items: center;
	gap: 20rpx;
}

.song-artist {
	font-size: 26rpx;
	color: #bfcfff;
}

.song-type {
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	border-radius: 12rpx;
	padding: 4rpx 12rpx;
}

.type-tag {
	font-size: 20rpx;
	color: #ffffff;
	font-weight: 500;
}

.song-actions {
	display: flex;
	align-items: center;
	gap: 20rpx;
	flex-shrink: 0;
}

.action-btn {
	padding: 12rpx;
	border-radius: 50%;
	transition: all 0.3s;

	&:active {
		transform: scale(0.9);
		background: rgba(255, 255, 255, 0.1);
	}
}

// 加载状态
.loading-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 120rpx 0;
	gap: 24rpx;
}

.loading-spinner {
	width: 50rpx;
	height: 50rpx;
	border: 4rpx solid #f3f3f3;
	border-top: 4rpx solid #667eea;
	border-radius: 50%;
	animation: spin 1s linear infinite;
}

.loading-spinner-small {
	width: 36rpx;
	height: 36rpx;
	border: 3rpx solid #f3f3f3;
	border-top: 3rpx solid #667eea;
	border-radius: 50%;
	animation: spin 1s linear infinite;
}

@keyframes spin {
	0% {
		transform: rotate(0deg);
	}

	100% {
		transform: rotate(360deg);
	}
}

.loading-text {
	font-size: 28rpx;
	color: #888888;
}

.loading-more {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 40rpx 0;
	gap: 16rpx;
}

.loading-more-text {
	font-size: 26rpx;
	color: #888888;
}

.no-more {
	display: flex;
	justify-content: center;
	padding: 40rpx 0;
}

.no-more-text {
	font-size: 26rpx;
	color: #666666;
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	height: 60vh;
	gap: 24rpx;
}

.empty-icon {
	font-size: 100rpx;
}

.empty-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #ffffff;
	margin-bottom: 8rpx;
}

.empty-desc {
	font-size: 28rpx;
	color: #888888;
}

// 歌曲操作弹窗
.song-action-popup {
	padding: 40rpx 32rpx 32rpx 32rpx;
	background: #23232b;
	border-radius: 20rpx 20rpx 0 0;
}

.popup-header {
	margin-bottom: 32rpx;
}

.popup-song-info {
	display: flex;
	align-items: center;
	gap: 24rpx;
}

.popup-song-details {
	flex: 1;
}

.popup-song-title {
	font-size: 32rpx;
	font-weight: 500;
	color: #ffffff;
	margin-bottom: 8rpx;
}

.popup-song-artist {
	font-size: 26rpx;
	color: #888888;
}

.action-list {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
	margin-bottom: 32rpx;
}

.action-item-popup {
	display: flex;
	align-items: center;
	gap: 24rpx;
	padding: 24rpx;
	background-color: #1a1a1f;
	border-radius: 16rpx;
	transition: all 0.3s;

	&:active {
		transform: scale(0.98);
		background-color: #2a2a2f;
	}
}

.action-text-popup {
	font-size: 32rpx;
	color: #ffffff;
}

.cancel-btn {
	margin-top: 20rpx;
}

// 播放预览弹窗
.play-popup {
	padding: 40rpx;
	background: #23232b;
	border-radius: 20rpx;
}

.play-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 40rpx;
}

.play-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #ffffff;
}

.play-content {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 24rpx;
}

.play-info {
	text-align: center;
}

.play-song-title {
	font-size: 30rpx;
	font-weight: 500;
	color: #ffffff;
	margin-bottom: 8rpx;
}

.play-song-artist {
	font-size: 26rpx;
	color: #888888;
}

.play-controls {
	margin-top: 24rpx;
}
</style>